Built-in R Features - Data Structures

R contains quite a few useful built-in functions to work with data structures. Here are some of the key functions to know:

  • seq(): Create sequences
  • sort(): Sort a vector
  • rev(): Reverse elements in object
  • str(): Show the structure of an object
  • append(): Merge objects together (works on vectors and lists)
In [8]:
# seq(start,end,step size)
seq(0, 100, by = 3)
Out[8]:
  1. 0
  2. 3
  3. 6
  4. 9
  5. 12
  6. 15
  7. 18
  8. 21
  9. 24
  10. 27
  11. 30
  12. 33
  13. 36
  14. 39
  15. 42
  16. 45
  17. 48
  18. 51
  19. 54
  20. 57
  21. 60
  22. 63
  23. 66
  24. 69
  25. 72
  26. 75
  27. 78
  28. 81
  29. 84
  30. 87
  31. 90
  32. 93
  33. 96
  34. 99
In [10]:
v <- c(1,4,6,7,2,13,2)
In [14]:
sort(v)
Out[14]:
  1. 1
  2. 2
  3. 2
  4. 4
  5. 6
  6. 7
  7. 13
In [15]:
sort(v,decreasing = TRUE)
Out[15]:
  1. 13
  2. 7
  3. 6
  4. 4
  5. 2
  6. 2
  7. 1
In [18]:
v2 <- c(1,2,3,4,5)
rev(v2)
Out[18]:
  1. 5
  2. 4
  3. 3
  4. 2
  5. 1
In [20]:
str(v)
 num [1:7] 1 4 6 7 2 13 2
In [22]:
append(v,v2)
Out[22]:
  1. 1
  2. 4
  3. 6
  4. 7
  5. 2
  6. 13
  7. 2
  8. 1
  9. 2
  10. 3
  11. 4
  12. 5
In [23]:
sort(append(v,v2))
Out[23]:
  1. 1
  2. 1
  3. 2
  4. 2
  5. 2
  6. 3
  7. 4
  8. 4
  9. 5
  10. 6
  11. 7
  12. 13

Data Types

  • is.*(): Check the class of an R object
  • as.*(): Convert R objects
In [1]:
v <- c(1,2,3)
is.vector(v)
Out[1]:
TRUE
In [2]:
is.list(v)
Out[2]:
FALSE
In [3]:
as.list(v)
Out[3]:
  1. 1
  2. 2
  3. 3
In [4]:
as.matrix(v)
Out[4]:
1
2
3

Great! That's if for the built-in data structure functions! These will com ein handy so try to remember them for the exercises!